package server.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;

public class ChatServer {


    public static void main(String[] args) {
        new ChatServer().build(8280);
    }
    public void build(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup  = new NioEventLoopGroup();
        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //option 和 childOption 是对通道的参数设置,  option是针对 bossGroup线程组, ChildOption是针对workerGroup线程组
//                    .option(ChannelOption.SO_BACKLOG,1024)  //Socket参数，服务端接受连接的队列长度，如果队列已满，客户端连接将被拒绝。
//                    .childOption(ChannelOption.SO_KEEPALIVE,true) //设置 通道保持链接
                    .handler(new LoggingHandler())       //此处 handler  是针对bossGroup 进行的操作, 是对请求链接进行处理, LoggingHandler为 netty提供的打印日志的handler ,需要自定义只需要 继承重写即可
                    .childHandler(new ChatServerChannelInitializer());
            ChannelFuture sync = b.bind(port).sync();
            System.out.println("netty服务端已启动,端口号为"+port);
            //服务端等待关闭
            sync.channel().closeFuture().sync();
            System.out.println("服务端开始关闭---");
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("启动netty服务异常");
        }finally{
            /**优雅退出，释放线程池资源*/
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("服务端已关闭!");
        }

    }
}
